<template>
  <div>
    <!-- 团体竞技成员选择 -->
    <van-popup v-model="dialogVisible" closeable position="bottom" :duration="0.16" :style="{ height: '100%' }">
      <van-loading v-if="dialogLoading" class="loadingStyle" />
      <div class="dialog_wrap">
        <div class="dialog_title gl_mb_15">成员选择</div>
        <!-- 分组模块 -->
        <div v-for="(item, index) in rightList" :key="index" class="member_item gl_mb_15">
          <div class="member_title gl_mb_15 gl_clear">
            <span class="gl_fl">{{ item.name }}</span>
            <van-icon class="icon_mt gl_fr" name="add-o" size="24" color="#0d97ef" @click="showActionSheet(item)" />
          </div>
          <div class="member_content">
            <div v-for="(jtem, jndex) in item._children" :key="jndex" class="gl_clear">
              <span class="gl_mr_5 gl_middle gl_fl">{{ jtem.name }}</span>
              <van-icon class="gl_middle gl_mr_5 gl_fr" name="cross" size="16" color="#c8c9cc" @click="removeMember(jtem, item)" />
            </div>
          </div>
        </div>

        <!-- 控制按钮 -->
        <van-row :gutter="10" class="bottom_btn_position">
          <van-col v-if="teamEntry.teamEntryId" span="12" align="center">
            <van-button type="danger" block @click="deleteGroup">删除整组</van-button>
          </van-col>
          <van-col :span="teamEntry.teamEntryId ? 12 : 24" align="center">
            <van-button type="info" block @click="submit()">确定</van-button>
          </van-col>
        </van-row>
      </div>
    </van-popup>
    <van-action-sheet
      v-model="actionVisible"
      :actions="leftList"
      cancel-text="取消"
      :description="leftList.length ? actionTitle : '暂无可选人员'"
      close-on-click-action
      @select="changeMemberToRight"
    />
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: '成员选择'
    },
    ignoreCheck: {
      type: Boolean,
      default: false
    },
    minSelectMemberNum: {
      type: Number,
      default: 1
    },
    maxSelectMemberNum: {
      type: Number,
      default: 0
    },
    requireMember: {
      type: Object,
      required: true,
      default() {
        return {};
      }
    },
    optionMember: {
      type: Array,
      default() {
        return [];
      }
    },
    selectMember: {
      type: Array,
      default() {
        return [];
      }
    },
    teamEntry: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data () {
    return {
      dialogVisible: false, // 成员选择模块显示控制
      actionVisible: false,
      dialogLoading: false, // 人员选择面板显示控制
      actionTitle: '',
      mainMember: {},
      leftList: [],
      rightList: [],
      currentContainer: ''
    };
  },
  watch: {
    dialogVisible (val) {
      if (!val) {
        // 窗口关闭
        this.mainMember = {};
        this.leftList = [];
        this.rightList = [];
      }
    }
  },
  methods: {
    // 打开
    open () {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.initData();
      });
    },
    close () {
      this.dialogLoading = false;
      this.dialogVisible = false;
    },
    hideLoading () {
      this.dialogLoading = false;
    },
    showActionSheet (item) {
      this.actionTitle = item.name + '成员选择';
      this.currentContainer = item;
      this.actionVisible = true;
    },
    // 初始化数据，拷贝数据
    initData() {
      const _mainMember = JSON.parse(JSON.stringify(this.requireMember));
      const _gender = this.matchMemberGender(_mainMember);
      _mainMember.name = _mainMember.name + _gender + ' (必选)';
      this.mainMember = _mainMember;

      let _optionMember = JSON.parse(JSON.stringify(this.optionMember)) || [];
      _optionMember = _optionMember.filter(item => {
        // 借助本次循环，调整显示名称 start
        item._name = item.name;
        const _gender = this.matchMemberGender(item);
        item.name = item.name + _gender;
        // end
        return item.id !== this.mainMember.id;
      });
      _optionMember.unshift(_mainMember);
      this.leftList = _optionMember;

      this.rightList = JSON.parse(JSON.stringify(this.selectMember));
      this.matchMainMemberFromRightList();
    },
    matchMemberGender (data) {
      let _gender = '';
      if (data.genderCode && data.genderCode === 'M') {
        _gender = ' (男)';
      }
      if (data.genderCode && data.genderCode === 'W') {
        _gender = ' (女)';
      }
      return _gender;
    },
    // 从右侧列表中：匹配必选人员是否存在；匹配左侧列表是否存该人员
    matchMainMemberFromRightList () {
      for (let i = 0; i < this.rightList.length; i++) {
        const item = this.rightList[i];
        for (let j = 0; j < item._children.length; j++) {
          const jtem = item._children[j];

          jtem._name = jtem.name;
          const _gender = this.matchMemberGender(jtem);
          jtem.name = jtem.name + _gender;

          const _jid = jtem.registerId || jtem.id;
          // 必选成员id
          const _mid = this.mainMember.registerId || this.mainMember.id;
          if (_mid === _jid) { // 找到了必选成员
            this.mainMember['disabled'] = true;
          } else { // 非必选成员
            const findMember = this.leftList.find(ktem => {
              const _kId = ktem.registerId || ktem.id;
              return _kId === _jid;
            });
            if (findMember) { // 在左侧列表找到该人员
              findMember['disabled'] = true;
            } else { // 在左侧列表没有找到该人员
              jtem['disabled'] = true;
              this.leftList.push(jtem);
            }
          }
        }
      }
    },
    // 确认按钮
    submit() {
      let _isPass = false;

      if (this.ignoreCheck) {
        _isPass = this.checkChooseListPass();
      } else {
        _isPass = this.checkChooseListPass(true);
      }

      if (_isPass) {
        const _rightList = JSON.parse(JSON.stringify(this.rightList));
        this.dialogLoading = true;
        this.$emit('onTeamCompetitionSubmit', _rightList);
      } else {
        console.log('_isPass false: TeamCompetition Template');
      }
    },
    // 校验选择的成员是否符合要求
    checkChooseListPass (checkMemberNum) {
      let _hasMainMember = false;
      let _seleceMemberLen = 0;
      for (let i = 0; i < this.rightList.length; i++) {
        const item = this.rightList[i];
        if (item._children.length) {
          _seleceMemberLen++;
        }
        item._children.forEach(jtem => {
          const _jid = jtem.registerId || jtem.id;
          const _mid = this.mainMember.registerId || this.mainMember.id;
          if (_jid === _mid) {
            _hasMainMember = true;
          }
        });
      }

      if (checkMemberNum && _seleceMemberLen < this.minSelectMemberNum) {
        this.$toast.fail(`最少应分配${this.minSelectMemberNum}名成员`);
        return false;
      }

      if (!_hasMainMember) {
        this.$toast.fail(`必选成员未被选择，所选成员中必须包含必选成员`);
        return false;
      }

      return true;
    },
    // 移除右侧成员
    removeMember (jtem, container, jndex) {
      const _jId = jtem.registerId || jtem.id;
      if (this.mainMember.id === _jId) {
        // 说明移除的人员是必选人员
        this.mainMember['disabled'] = false;
      } else {
        // 说明移除的人员是非必选人员
        jtem['disabled'] = false;
      }
      container._children.splice(jndex, 1);
    },
    // 将所选成员移至右侧
    changeMemberToRight (currentMember) {
      const container = this.currentContainer;

      if (container._children && container._children.length) {
        for (let i = 0; i < container._children.length; i++) {
          const item = container._children[i];
          const _iid = item.registerId || item.id;
          const _mid = this.mainMember.registerId || this.mainMember.id;
          if (_iid === _mid) {
            this.mainMember['disabled'] = false;
          } else {
            item['disabled'] = false;
          }
        }
      }
      currentMember['disabled'] = true;
      container._children = [currentMember];
      currentMember = '';
    },
    deleteGroup () {
      this.$dialog.confirm({
        title: '提示',
        message: '您确定要删除整组成员吗？'
      })
        .then(
          () => {
            this.dialogLoading = true;
            this.$emit('onDeleteGroupMember');
          }
        );
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog_wrap {
  padding: 0 15px 30px;
}
.dialog_title {
  height: 46px;
  font-size: 16px;
  line-height: 46px;
  color: #323233;
  font-weight: 500;
}
.member_item {
  padding: 10px 20px;
  padding-left: 20px;
  background: #ffffff;
  border-radius: 5px;
  box-shadow: 0 0 5px 0 rgba(0,0,0,0.10);
}

.member_title {
  line-height: 24px;
  font-size: 15px;
  color: #333;
  font-weight: bold;
}
.member_content {
  // padding: 10px 0;
  font-size: 14px;
  line-height: 16px;
  color: #333;
  vertical-align: middle;
}

.icon_mt {
  margin-top: 3px;
}

.loadingStyle {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  z-index: 11;
  background-color: rgba(255, 255, 255, 0.7);
  text-align: center;
}
</style>
